//
//  TeamViewController.m
//  NBAPro
//
//  Created by 李广松 on 16/7/9.
//  Copyright © 2016年 WYH. All rights reserved.
//

#import "TeamViewController.h"

@implementation TeamViewController {
    UITableView *eastTableView;
    UITableView *westTableView;
    
    NSMutableArray *eastTeamArr;
    NSMutableArray *westTeamArr;
    
    NSDictionary *eastTeamRankDic;
    NSDictionary *westTeamRankDic;

    
    NSMutableDictionary *eastTeamResultsDic;
    NSMutableDictionary *westTeamResultsDic;
    
    UILabel *titleLab;
    
    int index;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    index = 0;
    
    [self initialTeamData];
    
    UIView *titleView = [self createTitleViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150) AndBacngroundColor:[UIColor colorWithRed:80/255.0 green:164/255.0 blue:70/255.0 alpha:1]];
    [self.view addSubview:titleView];
    
    for (int i = 1610612737; i <= 1610612766; i++) {
        NSString *teamId = [[NSString alloc] initWithFormat:@"%d", i];
        [self getTeamInfoWithTeamId:teamId];
        
    }
 
}

#pragma mark - 获取球队信息
- (void)getTeamInfoWithTeamId:(NSString *)teamId {
    NSString *urlStr = [[NSString alloc] initWithFormat:@"%@teaminfocommon?LeagueID=00&SeasonType=Regular+Season&TeamID=%@&season=2015-16", API_BASE_URL_NBA, teamId];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            
            [self performSelectorOnMainThread:@selector(getTeamDetialInfo:) withObject:result waitUntilDone:YES];
        }
    }];
    [dataTask resume];
}


- (void)getTeamDetialInfo:(NSDictionary *)result {

    NSArray *teamInfoArr = result[@"resultSets"][0][@"rowSet"][0];

    index++;
    
    if ([teamInfoArr[5] isEqualToString:@"West"]) {
        
        [westTeamResultsDic setValue:result forKey:teamInfoArr[3]];
        [westTeamRankDic setValue:teamInfoArr[11] forKey:teamInfoArr[3]];
        
    }
    else {
        
        [eastTeamResultsDic setValue:result forKey:teamInfoArr[3]];

        [eastTeamRankDic setValue:teamInfoArr[11] forKey:teamInfoArr[3]];
    }
    
    if (index == 30) {
        [self sortTeam];
        [self createTableView];
        [self createPanGestureRecognizer];
    }

}


- (void)sortTeam {
    
    [self sortWithResult:westTeamResultsDic AndRank:westTeamRankDic AndTeam:westTeamArr];
    
    [self sortWithResult:eastTeamResultsDic AndRank:eastTeamRankDic AndTeam:eastTeamArr];
    
}

- (void)sortWithResult:(NSMutableDictionary *)resultDic AndRank:(NSDictionary *)rankDic AndTeam:(NSMutableArray *)teamArr {
    for (int i = 1; i <= resultDic.count; i++) {
        NSString *mark = [[NSString alloc] initWithFormat:@"%d", i];
        NSArray *keys = [rankDic allKeys];
        for (int j = 0; j < keys.count; j++) {
            id key = [keys objectAtIndex:j];
            NSString *rank = [[NSString alloc] initWithFormat:@"%@", [rankDic objectForKey:key]];
            if ([mark isEqualToString:rank]) {
                [teamArr addObject:key];
            }
        }
    }

}



#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == westTableView) {
        return westTeamArr.count;
    }
    else {
        return eastTeamArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    TeamInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[TeamInfoTableViewCell alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 88)];
    }
    if (indexPath.row % 2 == 0) {
        cell.backgroundColor = [UIColor colorWithRed:251/255.0 green:249/255.0 blue:251/255.0 alpha:1];
    }
    else {
        cell.backgroundColor = [UIColor colorWithRed:242/255.0 green:242/255.0 blue:242/255.0 alpha:1];
    }
    
    
    if (tableView == westTableView) {
        
        NSString *team = westTeamArr[indexPath.row];

        cell.teamName.text = team;
        cell.teamMark.text = [[NSString alloc] initWithFormat:@"%@ - %@", westTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][8], westTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][9]];
        cell.teamRank.text = [[NSString alloc] initWithFormat:@"%@",westTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][11]];
        
        if([westTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][2] isEqualToString:@"LA"]) {
            cell.teamCity.text = @"Los Angeles";
        }
        else {
            cell.teamCity.text = westTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][2];
        }
        if ([westTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][4] isEqualToString:@"HOU"]) {
            cell.teamIcon.image = [UIImage imageNamed: @"hou2"];
        }
        else {
            cell.teamIcon.image = [UIImage imageNamed: [westTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][4] lowercaseString]];
        }
        
    }
    else {
        NSString *team = eastTeamArr[indexPath.row];
        cell.teamName.text = team;
        cell.teamMark.text = [[NSString alloc] initWithFormat:@"%@ - %@", eastTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][8], eastTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][9]];
        cell.teamRank.text = [[NSString alloc] initWithFormat:@"%@",eastTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][11]];
        cell.teamCity.text = eastTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][2];
        cell.teamIcon.image = [UIImage imageNamed:[eastTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][4] lowercaseString]];
    }
    
    return cell;
}

- (UIView *)createCellViewWithTeamRank:(NSString *)rank AndCity:(NSString *)city AndName:(NSString *)name AndMark:(NSString *)mark AndIcon:(UIImage *)icon {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 88)];
    
    
    return view;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 88;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    TeamDetailInfoViewController *teamDetailInfoViewController;
    
    if (tableView == westTableView) {

        teamDetailInfoViewController = [self returnWestTeamDetailControllerWithIndex:(int)indexPath.row];

        
    }
    else {
        
        teamDetailInfoViewController = [self returnEastTeamDetailControllerWithIndex:(int)indexPath.row];
    }
    
    [self.navigationController pushViewController:teamDetailInfoViewController animated:YES];

}

- (NSDictionary *)getInfoDicWithDictionory:(NSDictionary *)dic AndTeam:(NSString *)team{
    NSString *teamId = [[NSString alloc] initWithFormat:@"%@", dic[team][@"resultSets"][0][@"rowSet"][0][0]];
    NSString *winStr = [[NSString alloc] initWithFormat:@"%@", dic[team][@"resultSets"][0][@"rowSet"][0][8]];
    NSString *loseStr = [[NSString alloc] initWithFormat:@"%@", dic[team][@"resultSets"][0][@"rowSet"][0][9]];
    NSString *conferenceRank = [[NSString alloc] initWithFormat:@"%@", dic[team][@"resultSets"][0][@"rowSet"][0][11]];
    NSString *divisionRank = [[NSString alloc] initWithFormat:@"%@", dic[team][@"resultSets"][0][@"rowSet"][0][12]];
    NSString *ppgRank = [[NSString alloc] initWithFormat:@"%@", dic[team][@"resultSets"][1][@"rowSet"][0][3]];
    NSString *rpgRank = [[NSString alloc] initWithFormat:@"%@", dic[team][@"resultSets"][1][@"rowSet"][0][5]];
    NSString *apgRank = [[NSString alloc] initWithFormat:@"%@", dic[team][@"resultSets"][1][@"rowSet"][0][7]];
    NSString *oppgRank = [[NSString alloc] initWithFormat:@"%@", dic[team][@"resultSets"][1][@"rowSet"][0][9]];

    NSDictionary *dictionary = @{ @"id":teamId, @"win":winStr, @"lose": loseStr, @"conferenceRank":conferenceRank, @"divisionRank":divisionRank, @"ppgRank":ppgRank, @"rpgRank": rpgRank, @"apgRank":apgRank, @"oppgRank": oppgRank };
    
    return dictionary;
    
}

#pragma mark - 界面
- (UIView *)createTitleViewWithFrame:(CGRect)frame AndBacngroundColor:(UIColor *)color{
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = color;
    
    titleLab = [CreateControl createLabelWithFrame:CGRectMake(20, 30, 200, 25) AndText:@"WESTERN" AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:23];
    titleLab.textAlignment = NSTextAlignmentLeft;
    [view addSubview:titleLab];
    
    UILabel *conferenceLab = [CreateControl createLabelWithFrame:CGRectMake(20, titleLab.frame.origin.y + titleLab.frame.size.height + 4, 100, 15) AndText:@"conference" AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:13];
    conferenceLab.textAlignment = NSTextAlignmentLeft;
    conferenceLab.font = [UIFont fontWithName:FONT_Hira size:13];
    [view addSubview:conferenceLab];
    
    return view;
}

- (void)createTableView {
    
    westTableView = [self createTableViewWithFrame:CGRectMake(0, 150, self.view.frame.size.width, self.view.frame.size.height - 150)];
    [self.view addSubview:westTableView];
    
    eastTableView = [self createTableViewWithFrame:CGRectMake(self.view.frame.size.width, 150, self.view.frame.size.width, self.view.frame.size.height - 150)];
    [self.view addSubview:eastTableView];
}

- (UITableView *)createTableViewWithFrame:(CGRect)frame {
    UITableView *tableView = [[UITableView alloc] initWithFrame:frame];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    return tableView;
}

- (void)initialTeamData {
    
    eastTeamArr = [[NSMutableArray alloc] init];
    westTeamArr = [[NSMutableArray alloc] init];
    
    eastTeamRankDic = [[NSMutableDictionary alloc] init];
    westTeamRankDic = [[NSMutableDictionary alloc] init];
    
    
    eastTeamResultsDic = [[NSMutableDictionary alloc] init];
    westTeamResultsDic = [[NSMutableDictionary alloc] init];
}


- (void)createPanGestureRecognizer {
    UISwipeGestureRecognizer *eastSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    [eastSwipeGesture setDirection:UISwipeGestureRecognizerDirectionRight];
    [eastTableView addGestureRecognizer:eastSwipeGesture];
    
    UISwipeGestureRecognizer *westSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    [westSwipeGesture setDirection:UISwipeGestureRecognizerDirectionLeft];
    [westTableView addGestureRecognizer:westSwipeGesture];
    
}

- (TeamDetailInfoViewController *)returnEastTeamDetailControllerWithIndex:(int)indexInt {
    TeamDetailInfoViewController *teamDetailInfoViewController = [[TeamDetailInfoViewController alloc] init];
    NSString *team = eastTeamArr[indexInt];
    NSDictionary *result = [self getInfoDicWithDictionory:eastTeamResultsDic AndTeam:team];
    teamDetailInfoViewController = [[TeamDetailInfoViewController alloc] initWithTeamId:result[@"id"] AndCity:eastTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][2] AndName:team AndIconStr:eastTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][4] AndWin:result[@"win"] AndLose:result[@"lose"] AndConference:eastTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][5] AndConferenceRank:result[@"conferenceRank"] AndDivision:eastTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][6] AndDivisionRank:result[@"divisionRank"] AndPPGRank:result[@"ppgRank"] AndRPGRank:result[@"rpgRank"] AndAPGRank:result[@"apgRank"] AndOPPGRank:result[@"oppgRank"]];
    
    return teamDetailInfoViewController;
    
}


- (TeamDetailInfoViewController *)returnWestTeamDetailControllerWithIndex:(int)indexInt {
    TeamDetailInfoViewController *teamDetailInfoViewController = [[TeamDetailInfoViewController alloc] init];
    
    NSString *team = westTeamArr[indexInt];
    NSString *cityStr;
    if([westTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][2] isEqualToString:@"LA"]) {
        cityStr = @"Los Angeles";
    }
    else {
        cityStr = westTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][2];
    }
    NSDictionary *result = [self getInfoDicWithDictionory:westTeamResultsDic AndTeam:team];
    teamDetailInfoViewController = [[TeamDetailInfoViewController alloc] initWithTeamId:result[@"id"] AndCity:cityStr AndName:team AndIconStr:westTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][4] AndWin:result[@"win"] AndLose:result[@"lose"] AndConference:westTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][5] AndConferenceRank:result[@"conferenceRank"] AndDivision:westTeamResultsDic[team][@"resultSets"][0][@"rowSet"][0][6] AndDivisionRank:result[@"divisionRank"] AndPPGRank:result[@"ppgRank"] AndRPGRank:result[@"rpgRank"] AndAPGRank:result[@"apgRank"] AndOPPGRank:result[@"oppgRank"]];
    
    return teamDetailInfoViewController;
    
}


- (void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer {
    if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        [self startAnimationWithFirstView:westTableView AndSecondView:eastTableView AndFirstFrame: CGRectMake(-self.view.frame.size.width, 150, self.view.frame.size.width, self.view.frame.size.height - 150) AndSecondFrame:CGRectMake(0, 150, self.view.frame.size.width, self.view.frame.size.height - 150)];
        titleLab.text = @"EASTERN";
    }
    if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        [self startAnimationWithFirstView:eastTableView AndSecondView:westTableView AndFirstFrame:CGRectMake(self.view.frame.size.width, 150, self.view.frame.size.width, self.view.frame.size.height - 150) AndSecondFrame:CGRectMake(0, 150, self.view.frame.size.width, self.view.frame.size.height - 150)];
        titleLab.text = @"WESTERN";
    }
    
}

- (void)startAnimationWithFirstView:(UIView *)first AndSecondView:(UIView *)second AndFirstFrame:(CGRect)firstFrame AndSecondFrame:(CGRect)secondFrame {
    [UIView beginAnimations:@"animationID" context:nil];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationRepeatAutoreverses:NO];
    first.frame = firstFrame;
    second.frame = secondFrame;
    [UIView commitAnimations];
}


- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
